package com.zhenyi.xhc.core;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;

import org.hashids.Hashids;

import com.jfinal.kit.StrKit;
import com.utils.PathUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpUtil;

public class DownloadUtils {

	public static void main(String[] args) {
		final Hashids piaoHashids = new Hashids("piao", 8);
		ExecutorService pool = ThreadUtil.newExecutor(5);
		for (long i = 1; i <= 200; i++) {
			String no = piaoHashids.encode(i);
			pool.execute(new Runnable() {

				@Override
				public void run() {
					// String code = "Experience_" + (10000 + i);
					String code = "Experience_" + no;
					File file = new File(PathUtils.getFile("logs", "xhccode", code + ".png"));
					if (file.exists()) {
						// continue;
						return;
					}
					String url = TicketUtils.qrcodeImage(code, code, "邀请体验票", "2019.1.15-2019.2.15");
					HttpUtil.downloadFile(url, file);
					System.out.println("down " + code + " ");
				}
			});
		}

		// new DownloadUtils().seo();
	}

	private String path = PathUtils.getFile("logs", "yitai", DateUtil.today(), "seo.txt");
	private FileWriter fileWriter = new FileWriter(path);

	private void query(String text) {
		if (StrKit.isBlank(text)) {
			return;
		}
		String url = "https://www.baidu.com/s?wd={}&pn={}&oq={}";
		int idx = 1;
		for (int page = 0; page < 10; page++) {
			String requestUrl = StrFormatter.format(url, text, page * 10, text);
			String response = HttpUtil.get(requestUrl);
			// System.out.println(response);
			boolean flag = response.contains("www.etcr.com");
			if (flag) {
				String word = "{}\t{}\n";
				word = StrFormatter.format(word, text, (page + 1));
				System.out.println(idx++ + " " + word);
				fileWriter.append(word);
				return;
			} else {
				// fileWriter.append(word);
				// System.out.println("page " + page + " no found");
			}
		}
	}

	public void seo() {
		String path = PathUtils.getFile("logs", "yitai", "seoword.txt");
		FileReader reader = new FileReader(path);
		List<String> line = reader.readLines();
		for (String string : line) {
			query(string);
		}
	}
}
